<script setup lang="ts">
defineOptions({
  name: "gasAtmosphere"
});

import { ref, nextTick, inject, onMounted, computed, getCurrentInstance } from "vue";
import { PxMessageBox } from "px-ui";
import fabBoardEchartsModelBoxItem from "../../fabBoardEchartsModelBoxItem.vue";
import { spcquerySpcAnalysis } from "@/api/spc";
import { getFabBoardPieData, getFabBoardBarData, getFabBoardEffluentData, getFabBoardSelectOptions } from "@/api/modules/fab";
import dayjs from "dayjs";

const { proxy }: any = getCurrentInstance();

const configOptions = inject("configOptions", ref<Array<any>>([]));
const gas_module_height = inject("gas_module_height", ref<string>(""));

const props = withDefaults(defineProps<{ area: string }>(), { area: "" });

const params = ref<Record<string, any> | null>(null);
const loading = ref<boolean>(false);
const target = ref<string>("");
const target_2 = ref<string>("");
const target_3 = ref<string>("");

// const atmosphereType = ref<string>("");
// const atmosphereTypeName = ref<string>("");

const atmosphereType = defineModel("atmosphereType", { type: String, default: "" });
const atmosphereTypeName = defineModel("atmosphereTypeName", { type: String, default: "" });

const barMaterialCode = ref<string>("");
const barAreaCode = ref<string>("");
const specialGasTypeOptions = ref<Array<any>>([]);

const gasConsumptionAreaRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const gasConsumptionTypeRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const gasPressureRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);

const gasConsumptionAreaData = ref<Record<string, any> | null>(null);
const gasConsumptionTypeData = ref<Record<string, any> | null>(null);
const gasPressureData = ref<Record<string, any> | null>(null);

const gasConsumptionAreaTitle = computed(() => `今日${atmosphereTypeName.value}用量区域占比`);
const gasConsumptionAreaDialogTitle = computed(() => `今日${atmosphereTypeName.value}用量区域统计`);
const gasConsumptionTypeTitle = computed(() => `${atmosphereTypeName.value}用量统计`);
const gasPressureTitle = computed(() => `${atmosphereTypeName.value}供应压力`);

const gasConsumptionAreaUnit = computed(() => `m³`);
const gasConsumptionTypeUnit = computed(() => `m³`);
const gasPressureUnit = computed(() => `Pa`);

const mapConfigOptionsFn = () => {
  const c = configOptions.value.find(item => item.className === "GAS" && item.chartType === "pie" && item.systemId === atmosphereType.value);
  const d = configOptions.value.find(
    item => item.className === "GAS" && item.chartType === "column" && item.areaId === props.area && item.systemId === atmosphereType.value
  );
  const e = configOptions.value.find(
    item => item.className === "GAS" && item.chartType === "spc" && item.areaId === props.area && item.systemId === atmosphereType.value
  );
  target.value = c?.quotaCode;
  target_2.value = d?.quotaCode;
  target_3.value = e?.quotaCode;
  barMaterialCode.value = target_2.value;
  barAreaCode.value = props.area === "ALL" ? null : props.area;
};

// const specialGasTypeChangeHandler = async (val: string, flag: boolean = false) => {
//   const t = specialGasTypeOptions.value.find(item => item.value === val);
//   atmosphereTypeName.value = t.label;
//   initData();
//   await init(flag);
// };

const startLoading = () => {
  loading.value = true;
};

const closeLoading = () => {
  loading.value = false;
};

// 请求饼图数据
const queryPieDataFn = async (cb?: () => void) => {
  if (!target.value) {
    cb && cb();
    return;
  }
  const params = { materialCode: target.value };
  gasConsumptionAreaRef.value.loading = true;
  const res = await getFabBoardPieData(params, () => {
    closeLoading();
    gasConsumptionAreaRef.value.loading = false;
  });
  gasConsumptionAreaData.value = res;
  cb && cb();
};

// 请求柱状图数据
const queryBarDataFn = async (cb?: () => void) => {
  if (!target_2.value) {
    cb && cb();
    return;
  }
  const areaCode = props.area === "ALL" ? null : props.area;
  const params = { materialCode: target_2.value, areaCode };
  gasConsumptionTypeRef.value.loading = true;
  const res = await getFabBoardBarData(params, () => {
    closeLoading();
    gasConsumptionTypeRef.value.loading = false;
  });
  gasConsumptionTypeData.value = res;
  cb && cb();
};

const exportDataHandler = (data: Record<string, any> = {}) => {
  const { point = "" } = data;
  const pointList = [point];
  proxy.download("post", "/operation/api/v1/spcIndicator/querySpcAnalysis/export", { ...params.value, pointList });
  PxMessageBox.alert("正在导出数据，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "导出数据", {
    confirmButtonText: "我知道了"
  });
};

const getLineParams = () => {
  const startTime = dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss");
  const endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  const timePeriod = "minutes";
  // 调试
  // const timePeriod = "hour";
  const jobIdList = null;
  const pointList = [target_3.value];
  params.value = { startTime, endTime, timePeriod, jobIdList, pointList };
};

// 请求折现图数据
const queryLineDataFn = async (cb?: () => void) => {
  getLineParams();
  gasPressureRef.value.loading = true;
  const res = await spcquerySpcAnalysis({ ...params.value }, () => {
    closeLoading();
    gasPressureRef.value.loading = false;
  });
  gasPressureData.value = res.find(item => item.point === target_3.value);
  cb && cb();
};

// const querySelectOptionsFn = async (cb?: () => void) => {
//   if (!!specialGasTypeOptions.value?.length) {
//     cb && cb();
//     return;
//   }
//   // gasName      SPECIALTY    CHEMICALS   ATMOSPHERIC
//   const params = { className: "GAS", gasName: "ATMOSPHERIC" };
//   const res = await getFabBoardSelectOptions(params);
//   specialGasTypeOptions.value = res.map((item: any) => ({ ...item, value: item.systemId, label: item.systemName }));
//   atmosphereType.value = specialGasTypeOptions.value[0].value;
//   atmosphereTypeName.value = specialGasTypeOptions.value[0].label;
//   cb && cb();
// };

const init = async (flag: boolean = false) => {
  startLoading();
  queryPieDataFn(async () => {
    await nextTick();
    gasConsumptionAreaRef.value?.init(flag);
  });
  queryBarDataFn(async () => {
    await nextTick();
    gasConsumptionTypeRef.value?.init(flag);
  });
  queryLineDataFn(async () => {
    await nextTick();
    gasPressureRef.value?.init(flag);
  });
  closeLoading();
};

const initData = () => {
  gasConsumptionAreaData.value = null;
  gasConsumptionTypeData.value = null;
  gasPressureData.value = null;
  mapConfigOptionsFn();
};

defineExpose({
  init,
  initData
  // querySelectOptionsFn
});
</script>

<template>
  <div class="gas-atmosphere-gas-content">
    <fabBoardEchartsModelBoxItem
      ref="gasConsumptionAreaRef"
      exportImage
      echartsType="pie"
      eventType="areaCode"
      :materialCode="target"
      :dialogTitle="gasConsumptionAreaDialogTitle"
      :title="gasConsumptionAreaTitle"
      :unit="gasConsumptionAreaUnit"
      :data="gasConsumptionAreaData"
    >
      <!-- <template #headLeft>
        <px-select v-model="atmosphereType" style="width: 120px" size="small" placeholder="请选择大宗气体类型" @change="specialGasTypeChangeHandler">
          <px-option v-for="item in specialGasTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </template> -->
    </fabBoardEchartsModelBoxItem>
    <fabBoardEchartsModelBoxItem
      ref="gasConsumptionTypeRef"
      exportImage
      echartsType="bar"
      :materialCode="barMaterialCode"
      :areaCode="barAreaCode"
      :title="gasConsumptionTypeTitle"
      :unit="gasConsumptionTypeUnit"
      :data="gasConsumptionTypeData"
    />
    <fabBoardEchartsModelBoxItem
      ref="gasPressureRef"
      exportImage
      exportData
      :title="gasPressureTitle"
      :unit="gasPressureUnit"
      :data="gasPressureData"
      @exportDataChange="exportDataHandler(gasPressureData)"
    />
  </div>
</template>

<style lang="scss" scoped>
.gas-atmosphere-gas-content {
  display: grid;
  grid-template-rows: repeat(1, 100%);
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  width: 100%;
  height: 100%;
}
</style>
